package com.insurance.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.insurance.common.common.ResponseData;
import com.insurance.common.enums.CommonEnum;
import com.insurance.common.utils.JwtOperatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * @author Style
 * @version 1.0
 * @date 2020/12/5
 **/
@Slf4j
public class CustomeFilter extends GenericFilterBean {

    private static List<String> ignoreUrlList = Arrays.asList("/authentication/doLogin");

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String requestUrl = req.getServletPath();
        if(ignoreUrlList.contains(requestUrl)){
            chain.doFilter(request, response);
        }else{
            try {
                String token = req.getHeader("Authorization");
                if(StringUtils.isBlank(token) || JwtOperatorUtil.isTokenExpired(token)){
                    ResponseData errorResponseData = ResponseData.error(CommonEnum.TOKEN_ERROR);
                    res.setContentType("application/json;charset=utf-8");
                    PrintWriter out = res.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(errorResponseData));
                    out.flush();
                    out.close();
                }else{
                    chain.doFilter(request, response);
                }
            } catch (Exception e) {
                ResponseData errorResponseData = ResponseData.error(CommonEnum.TOKEN_ERROR);
                res.setContentType("application/json;charset=utf-8");
                PrintWriter out = res.getWriter();
                out.write(new ObjectMapper().writeValueAsString(errorResponseData));
                out.flush();
                out.close();
            }
        }

    }
}
